<template>
  <div>
    <div class="m-2">
      <ElButton @click="[(code = 'submit'), (visviableDialog = true)]">添加路由</ElButton>
    </div>
    router
    <SvgIcon name="clone"></SvgIcon>>
    <el-scrollbar height="calc(100vh - 101px)">
      <ElTable :data="pageData.list" class="w-[100%]" border>
        <ElTableColumn prop="id" label="ID" width="80px" align="center"></ElTableColumn>
        <ElTableColumn prop="parent_id" label="父级ID" width="80px" align="center"></ElTableColumn>
        <ElTableColumn prop="name" label="路由名称" align="center"></ElTableColumn>
        <ElTableColumn prop="path" label="路由路径" align="center"></ElTableColumn>
        <ElTableColumn prop="component" label="组件位置" align="center"></ElTableColumn>

        <ElTableColumn prop="icon" label="图标" align="center">
          <template #default="{ row }">
            {{ row.icon ? row.icon : '暂无图标' }}
          </template>
        </ElTableColumn>
        <ElTableColumn prop="status" label="路由状态" align="center">
          <template #default="{ row }">
            <el-tag v-if="row.status" type="success" @click="toggleDisable(row)">正常</el-tag>
            <el-tag v-else type="danger" @click="toggleDisable(row)">禁用</el-tag>
          </template>
        </ElTableColumn>
        <ElTableColumn prop="frameSrc" label="外链地址" align="center"></ElTableColumn>
        <ElTableColumn prop="frameSrcType" label="外链地址" align="center">
          <template #default="{ row }">
            <el-tag v-if="row.frameSrcType == '_self'" type="success">当前页</el-tag>
            <el-tag v-else @click="toggleDisable(row)">新开页</el-tag>
          </template>
        </ElTableColumn>
        <ElTableColumn prop="meta" label="菜单标题" align="center">
          <template #default="{ row }">
            {{ JSON.parse(row.meta).title }}
          </template>
        </ElTableColumn>
        <ElTableColumn prop="remark" width="300px" label="路由备注" align="center">
          <template #default="{ row }">
            {{ row.remark ? row.remark : '暂无备注' }}
          </template>
        </ElTableColumn>
        <ElTableColumn label="操作" align="center" width="160px">
          <template #default="{ row }">
            <ElButton @click="[(visviableDialog = true), (formData = row), (code = 'change')]"
              >编辑</ElButton
            >
            <ElButton type="danger" @click="deleteRouter(row.id)">删除</ElButton>
          </template>
        </ElTableColumn>
      </ElTable>
      <!-- 分页器 -->
      <ElPagination
        :current-page="pageData.page"
        :page-sizes="[10, 20, 30, 40]"
        :page-size="pageData.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="pageData.total"
        class="mt-2 float-right mr-5"
        @size-change="sizeChange"
        @current-change="currentChange"
      ></ElPagination>
    </el-scrollbar>
    <!-- 添加修改路由弹窗 -->
    <ElDialog v-model="visviableDialog" :title="code == 'submit' ? '添加路由' : '编辑路由'">
      <ElForm v-model="formData">
        <ElFormItem label="父级ID">
          <el-tree-select
            ref="tree"
            v-model="formData.parent_id"
            :props="{
              label: 'name',
              children: 'children'
            }"
            show-checkbox
            node-key="id"
            default-expand-all
            check-strictly
            accordion
            :data="treeDataList"
          ></el-tree-select>
        </ElFormItem>
        <ElFormItem label="路由名称" prop="name">
          <ElInput v-model="formData.name" placeholder="请输入路由名称"></ElInput>
        </ElFormItem>
        <ElFormItem label="路由路径" prop="path">
          <ElInput v-model="formData.path" placeholder="请输入路由路径"></ElInput>
        </ElFormItem>
        <ElFormItem label="组件位置" prop="component">
          <ElSelect v-model="formData.component">
            <ElOption
              v-for="item in resultFilesPath"
              :key="item"
              :label="item"
              :value="item"
            ></ElOption>
          </ElSelect>
        </ElFormItem>
        <ElFormItem label="路由备注" prop="path">
          <ElInput v-model="formData.remark" placeholder="请输入路由备注"></ElInput>
        </ElFormItem>
        <ElFormItem label="菜单标题" prop="frameSrc">
          <ElInput v-model="formData.meta.title" placeholder="请输入菜单标题"></ElInput>
        </ElFormItem>
        <ElFormItem label="图标" prop="icon" :data="iconList">
          <el-select v-model="formData.icon" placeholder="Select">
            <el-option-group v-for="group in iconList" :key="group" :label="group.label">
              <el-option v-for="item in group.options" :key="item" :label="item" :value="item">
                <ElIcon v-if="item.indexOf('icon') == -1" :icon="item">
                  <component :is="item"></component>
                </ElIcon>
                <ElIcon v-else :icon="item">
                  <SvgIcon :name="item.replace('icon-', '')" />
                </ElIcon>
                <span class="float-right">
                  {{ item }}
                </span></el-option
              >
            </el-option-group>
          </el-select>
          <ElIcon
            v-if="formData.icon && formData.icon.indexOf('icon') == -1"
            size="26px"
            class="ml-3"
            :icon="formData.icon"
          >
            <component :is="formData.icon"></component>
          </ElIcon>
          <SvgIcon
            v-if="formData.icon && formData.icon.indexOf('icon') != -1"
            size="26"
            class="ml-3"
            :name="formData.icon.replace('icon-', '')"
          />
        </ElFormItem>
        <ElFormItem label="路由标题" prop="title">
          <ElInput v-model="formData.title" placeholder="路由标题"></ElInput>
        </ElFormItem>
        <ElFormItem label="外链方式" prop="frameSrcType">
          <ElRadioGroup v-model="formData.frameSrcType">
            <ElRadioButton label="_self">当前页</ElRadioButton>
            <ElRadioButton label="_blank">新网页</ElRadioButton>
          </ElRadioGroup>
        </ElFormItem>
        <ElFormItem label="是否隐藏" prop="hidden">
          <ElRadioGroup v-model="formData.hidden">
            <ElRadioButton label="0">显示</ElRadioButton>
            <ElRadioButton label="1">隐藏</ElRadioButton>
          </ElRadioGroup>
        </ElFormItem>

        <ElFormItem label="路由固定" prop="status">
          <ElRadioGroup v-model="formData.isAffix">
            <ElRadioButton label="0">是</ElRadioButton>
            <ElRadioButton label="1">否</ElRadioButton>
          </ElRadioGroup>
        </ElFormItem>
        <ElFormItem label="是否缓存" prop="status">
          <ElRadioGroup v-model="formData.isCache">
            <ElRadioButton label="0">否</ElRadioButton>
            <ElRadioButton label="1">是</ElRadioButton>
          </ElRadioGroup>
        </ElFormItem>
        <ElFormItem label="路由状态" prop="status">
          <ElRadioGroup v-model="formData.status">
            <ElRadioButton label="0">禁用</ElRadioButton>
            <ElRadioButton label="1">正常</ElRadioButton>
          </ElRadioGroup>
        </ElFormItem>
        <ElFormItem label="排序" prop="sort">
          <ElInputNumber
            v-model="formData.sort"
            placeholder="请输入排序"
            class="!w-full"
          ></ElInputNumber>
        </ElFormItem>
      </ElForm>
      <template #footer>
        <ElButton @click="visviableDialog = false">取消</ElButton>
        <ElButton type="primary" @click="submit">提交</ElButton>
      </template>
    </ElDialog>
  </div>
</template>

<script setup>
import * as icons from '@element-plus/icons-vue'
const routerApi = useRouterApi()
const formData = ref({
  meta: {
    title: ''
  }
})
const { getAllViewsFiles, getAllSvgIconsFiles } = getViewsFiles()
const hasFiles = getAllViewsFiles()
const resultFilesPath = ref(
  Object.keys(hasFiles).map((item) => {
    return item.replace('/src/views', '').replace('.vue', '')
  })
)
// const iconRouter = ref('')
const code = ref('')
// const tree = ref(null)
const visviableDialog = ref(false)

//用户列表
const pageData = ref({
  list: [],
  total: 100,
  page: 1,
  pageSize: 10
})
//树形结构
const treeDataList = ref([])
const iconList = ref([
  {
    label: '组件库图标',
    options: Object.keys(icons).map((item) => {
      return item
    })
  },
  {
    label: '自定义图标',
    options: getAllSvgIconsFiles()
  }
])

// console.log(iconList.value)
//提交
const submit = () => {
  let cloneData = JSON.parse(JSON.stringify(formData.value))
  cloneData.meta = JSON.stringify(cloneData.meta)
  formData.value.meta = cloneData.meta
  if (code.value == 'submit') {
    console.log(formData.value)
    routerApi.createRouter(formData.value).then(() => {
      visviableDialog.value = false
      getRouterList()
      return successElMessageBox('提交成功')
    })
  } else {
    routerApi.updateRouter(formData.value).then(() => {
      visviableDialog.value = false
      getRouterList()
      successElMessageBox('修改成功')
    })
  }
}
//删除路由
const deleteRouter = (id) => {
  ElMessageBox.confirm('是否确认删除', '提示', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(() => {
      routerApi.deleteRouter(id).then(() => {
        getRouterList()
        successElMessageBox('删除成功')
      })
    })
    .catch(() => {
      errorElMessageBox()
    })
}

//更改路由状态
const toggleDisable = (row) => {
  routerApi
    .updateRouterStatus({
      id: row.id,
      status: 0
    })
    .then((res) => {
      console.log(res)
      getRouterList()
      successElMessageBox('修改成功')
    })
}

//获取路由列表
routerApi.getRouterList().then((res) => {
  // console.log(res);
  pageData.value.total = res.count
  // console.log(res);
})
onMounted(() => {
  getRouterList()
  // console.log(icons)
})

const getRouterList = () => {
  routerApi
    .getRouterList({
      page: pageData.value.page,
      limit: pageData.value.pageSize
    })
    .then((res) => {
      pageData.value.list = res.rows
    })
}
//选择图片

//分页器·
const sizeChange = (val) => {
  pageData.value.pageSize = val
  getRouterList()
}
const currentChange = (val) => {
  pageData.value.page = val
  getRouterList()
}
//发送弹框
const errorElMessageBox = () => {
  ElMessage({
    type: 'error',
    message: '已取消'
  })
}
const successElMessageBox = (res) => {
  ElMessage({
    type: 'success',
    message: res
  })
}
//获取树形结构
routerApi.treeDataList().then((res) => {
  treeDataList.value = res
})
</script>

<style lang="scss" scoped></style>
